Imports System.Collections.Generic
Imports System.Web.Services

Partial Class login
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, _
                            ByVal e As System.EventArgs) _
                            Handles Me.Load

        Try

        
            Trace.Write("Begin Load")
            Dim passwordConfig As Cdm.DataCore.LookupTables.LuPasswordConfiguration = Cdm.DataCore.LookupTables.LuPasswordConfiguration.Retrieve()
            Me.PasswordTextBox.MaxLength = passwordConfig.PasswordLength
            Me.UserIdTextBox.MaxLength = passwordConfig.UseridLength
            Me.SetFocus(Me.UserIdTextBox)
            Me.Title = "Login Page"

            If Not Page.IsPostBack Then
                Trace.Write("First Load")
                ' Set login attempt tracker variable to 0 if it doesn't exist and it's not tured off (i.e. set to 0).
                If Session("LoginAttempts") Is Nothing And passwordConfig.LockOutAttempts <> 0 Then
                    Session("LoginAttempts") = 0
                Else
                    Session("LoginAttempts") = -1
                End If


                'Get the Application Settings
                Dim appSettings As List(Of Cdm.DataCore.LookupTables.LuApplicationSettings)
                appSettings = Cdm.DataCore.LookupTables.LuApplicationSettings.ListAll()

                Trace.Write("Retrieve AppSettings")
                For i As Integer = 0 To appSettings.Count - 1
                    Application(appSettings.Item(i).SettingName) = appSettings.Item(i).SettingValue
                Next

                Me.imgLogo.ImageUrl = FullPath(Application("CurrentLogo"))
                Me.imgLogo.AlternateText = Application("StateDeptName")
                Me.lblAppName.Text = Application("AppName")
                Me.lblDeptName.Text = Application("StateDeptName")

            End If

            Trace.Write("Load Complete")

        Catch ex As Exception
            Me.ErrorLabel.Text = "Error Loading Application:" + ex.Message
            Trace.Write(ex.Message)
            If (Not ex.InnerException Is Nothing) Then
                Trace.Write(ex.InnerException.Message)
            End If
        End Try


    End Sub

    Protected Sub LoginButton_Click(ByVal sender As Object, _
                                    ByVal e As System.EventArgs) _
                                    Handles LoginButton.Click

        Trace.Write("Login Button Pressed")
        Dim passwordConfig As Cdm.DataCore.LookupTables.LuPasswordConfiguration = Cdm.DataCore.LookupTables.LuPasswordConfiguration.Retrieve()
        If Session("LoginAttempts") <> -1 Then
            Session("LoginAttempts") += 1
            Trace.Write("Login Attempts Incremented to " + Session("LoginAttempts").ToString())
        End If

        If CInt(Session("LoginAttempts")) < passwordConfig.LockOutAttempts OrElse CInt(Session("LoginAttempts")) <> -1 Then

            Trace.Write("About to call LoginUser method")
            Dim loginResult As Integer = (UserAuthorization.LoginUser(Me.UserIdTextBox.Text, Me.PasswordTextBox.Text))
            Trace.Write("Return from LoginUser method")
            If Not Session("LoginId") Is Nothing Then
                Trace.Write("Session Login Id = " + Session("LoginId"))
            Else
                Trace.Write("Session Login id has not been set.")
            End If

            If loginResult = UserAuthorization.LoginStatus.Authenticated Then

                Try

                    Trace.Write("Login Authentication")
                    Dim Participant As New Cdm.DataCore.Entities.Participant()

                    Participant = EntityController.GetParticipant()
                    If Not Participant Is Nothing Then
                        Trace.Write("Participant User")
                        Session("ParticipantId") = Participant.ParticipantId
                    End If
                    EntityController.SetApplicationDisplayNames(True)
                    Trace.Write("Application DisplayNames set; about to set cookie")
                    FormsAuthentication.SetAuthCookie(UserAuthorization.CurrentUser.LogonId, False, "/")
                    Trace.Write("about to RedirectFrom Login page")
                    FormsAuthentication.RedirectFromLoginPage(UserAuthorization.CurrentUser.LogonId, False, "/")

                Catch ex As Exception
                    Trace.Write("Exception occurred in the Login Button procedure:  " + ex.Message)
                    Response.Redirect("default.aspx")
                Finally
                    Response.Redirect("default.aspx")

                End Try

            ElseIf loginResult = UserAuthorization.LoginStatus.Expired Then
                Dim Participant As New Cdm.DataCore.Entities.Participant()

                Participant = EntityController.GetParticipant()
                If Not Participant Is Nothing Then
                    Session("ParticipantId") = Participant.ParticipantId
                End If
                EntityController.SetApplicationDisplayNames(True)
                FormsAuthentication.SetAuthCookie(UserAuthorization.CurrentUser.LogonId, False, "/")

                Me.ErrorLabel.Text = "Your password has expired.  Please change your password. <br /><a href='ChangePassword.aspx'>Change Password</a>"
                Me.ErrorLabel.Visible = True
                Me.Title = "Login Page - Password Expired."
            ElseIf loginResult = UserAuthorization.LoginStatus.NotAuthenticated Then

                Me.ErrorLabel.Text = "Login failed.  Please try again."
                Me.ErrorLabel.Visible = True
                Me.Title = "Login Page - Attempt failed."
            End If

        Else

            Me.ErrorLabel.Visible = True
            Me.ErrorLabel.Text = "You've made too many failed attempts to login.  Please contact your system administrator."
            Me.Title = "Login Page - Password Attempts Exceeded."
        End If

    End Sub


    Public Shared Function FullPath(ByVal pathName As String) As String

        If pathName.StartsWith("~") Then


            If pathName.Length > 1 Then
                Return System.Web.HttpContext.Current.Request.ApplicationPath & pathName.Substring(1)
            Else
                Return System.Web.HttpContext.Current.Request.ApplicationPath
            End If
        Else
            Return pathName
        End If
    End Function

    Private Function GetHostName(ByVal isSecure As Boolean) As String
        If isSecure Or System.Web.HttpContext.Current.Request.Url.Port = 80 Then
            Return System.Web.HttpContext.Current.Request.Url.Host
        Else
            Return System.Web.HttpContext.Current.Request.Url.Host() & ":" & System.Web.HttpContext.Current.Request.Url.Port.ToString()
        End If
    End Function

    Protected Sub ForgotPasswordLinkButton_Click(ByVal sender As Object, _
                                                 ByVal e As System.EventArgs) _
                                                 Handles ForgotPasswordLinkButton.Click

        Me.ErrorLabel.Visible = False
        Me.MessageLabel.Visible = False

        ' Email user, if they exist, with their user id and password.
        If Me.UserIdTextBox.Text <> "" Then

            Dim user As Cdm.DataCore.UserSecurity.CDMUser = Cdm.DataCore.UserSecurity.CDMUser.Retrieve(Me.UserIdTextBox.Text)
            If user IsNot Nothing Then

                If user.EmailAddress <> "" Then

                    ' Set up the body of the email.
                    Dim emailBody As New StringBuilder
                    emailBody.Append("Dear " & user.FirstName & " " & user.LastName & "," & vbCrLf & vbCrLf)
                    emailBody.Append("Here is your username and password for " & Application("AppName") & "." & vbCrLf & vbCrLf)
                    emailBody.Append(vbTab & "User Id: " & user.LogonId & vbCrLf)
                    emailBody.Append(vbTab & "Password: " & user.Password & vbCrLf)
                    emailBody.Append(vbTab & "This password expires on " & user.PasswordExpires.ToString)

                    ' Send the email.
                    Cdm.AppServices.SendEmail.Send(Application("EmailServer"), _
                                                   Application("EmailFromAddress"), _
                                                   Application("EmailFromDisplayName"), _
                                                   user.EmailAddress, _
                                                   "Your user id and password.", _
                                                   emailBody.ToString)

                    MessageLabel.Visible = True
                    MessageLabel.Text = "An email has been sent to you with your login information."
                    Me.Title = "Login Page - Email sent."
                Else
                    Me.Title = "Login Page - Error Sending User Info."
                    Me.ErrorLabel.Visible = True
                    Me.ErrorLabel.Text = "Email address for " & user.FirstName & " " & user.LastName & " does not exist."

                End If

            End If

        Else

            Me.ErrorLabel.Visible = True
            Me.ErrorLabel.Text = "Please enter a user id."

        End If

    End Sub


End Class
